package com.ebt.m.proposal_v2.dao.file;

import android.text.TextUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * @author archer.qi
 *         Created on 2017/6/1.
 */
public class DiskUtils {

    /**
     * 生成一个空文件
     *
     * @param fileName
     * @return
     */
    public static File createNewFile(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        String dir = file.getParentFile().getPath();
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 文件保存
     *
     * @param targetFile
     * @param source
     * @return
     */
    public static boolean OkioWrite(File targetFile, BufferedSource source) {
        BufferedSink sink = null;
        boolean okioWriteSucceed = false;
        try {
            sink = Okio.buffer(Okio.sink(targetFile));
            sink.writeAll(source);
            okioWriteSucceed = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sink != null) {
                try {
                    sink.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return okioWriteSucceed;
    }

    /**
     * 删除文件
     *
     * @param fileName
     */
    public static void deleteFile(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return;
        }
        File file = new File(fileName);
        file.deleteOnExit();
    }

    /**
     * 文件是否存在
     *
     * @param fileName
     * @return
     */
    public static boolean isFileExists(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return false;
        }
        return new File(fileName).exists();
    }
}
